package com.lg.service.impl;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lg.mapper.JobMapper;
import com.lg.pojo.JobInfo;
import com.lg.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class JobServiceImpl implements JobService {

    private static final String CACHE_KEY_PREFIX = "jobinfo:";

    private LoadingCache<String, JobInfo> jobInfoCache;

    @Autowired
    private JobMapper jobMapper;

    @PostConstruct
    private void initCache() {
        // 初始化 jobInfo 的本地缓存
        jobInfoCache = CacheBuilder.newBuilder()
                .concurrencyLevel(Runtime.getRuntime().availableProcessors())
                .maximumSize(3000)
                // 过期时间:10s
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .build(new CacheLoader<String, JobInfo>() {
                    @Override
                    public JobInfo load(String key) throws Exception {
                        // 从 DB 中获取
                        Long id = getIdFromCacheKey(key);

                        // 存入guavaCache
                        return jobMapper.selectJobInfoById(id);
                    }
                });
    }

    @Override
    public boolean createNewJob(JobInfo jobInfo) {
        return jobMapper.createNewJob(jobInfo);
    }

    @Override
    public JobInfo selectJobInfoById(Long id) {
        try {
            String cacheKey = getCacheKey(id);

            log.info("本次查询的id：{}", id);

            return jobInfoCache.get(cacheKey);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean updateJobInfo(JobInfo jobInfo) {
        try {
            Long id = jobInfo.getId();
            String cacheKey = getCacheKey(id);
            jobMapper.updateJobInfo(jobInfo);
            jobInfoCache.invalidate(cacheKey);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteJobInfo(Long id) {
        try {
            String cacheKey = getCacheKey(id);
            jobMapper.deleteJobInfo(id);
            jobInfoCache.invalidate(cacheKey);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private String getCacheKey(Long id) {
        return CACHE_KEY_PREFIX.concat(String.valueOf(id));
    }

    private Long getIdFromCacheKey(String key) {
        return Long.valueOf(key.substring(CACHE_KEY_PREFIX.length()));
    }

}
